<?

/*	Social.facebook OBJECT
 *	
 *	Facebook module with several actions
 		> like button (iframe AND without iframe)
 		> recommend button
 		> filter bio, image, friends count, link, picture, 
 		> filter posted messages (by id or by friends of id)
 		> keyword search through public facebook pages all over the world (movies vs messages)     
 *
 *  Should be expandable to more complicated facebook integrations and fb applications
 *  
 *  @author: oneDot only .
 *  @date: 2010-06-03
 *
 */

// include of the facebook class (external class by facebook)
require_once ROOT . 'engine/ext/facebook/fb.php';

class SocialFacebook extends MOD {

	function __construct( $vars ) {

		$this->_addvars( $vars );
		$this->_ref();
	}
	
	// output function
	public function output() { 
	
		if( $this->action ) $result = $this->{ "filter_" . $this->action }();
		
		// add css & show variables
		if ( $result ) {
			$this->addclass( $this->action );
			$result = implode( "\n", $result );
		}
		
		// initiliaze facebook
		$result .= '<script>FB.init("' . engine_get("json:social.facebook.account")->appapi . '", "' . ROOT . 'engine/ext/facebook/xd_receiver.htm");</script>';
		$result .= '<script type="text/javascript" src="http://static.ak.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/it_IT"></script>';
		return $this->parse( $result );
	
	}
	
	
	// output friends (scraping)
	private function filter_friends() {
		
		// setup scrape tool
		$content	= json_decode(file_get_contents('https://graph.facebook.com/' . engine_get("json:social.facebook.account")->account . '?' . $this->connect_fb()));
		$url		= $content->link . '?v=info';
		$scrape		= new Scrape();
		
		// start scraping
		$scrape->fetch($url);
		$data		= $scrape->removeNewLines($scrape->result);
				
		// select data
		$data = $scrape->fetchBetween('<div class="UIGridRenderer','</a></div></div></div></div>',$data,true);
		$rows = $scrape->fetchAllBetween('<div class="UIGridRenderer_Row clearfix">','</a></div></div></div>',$data,true);
			
		// row by row add to table
		$i = 0; 		// cell counter for rows
		$return[] = '<table class="posts friends" width="100%">';
		foreach ($rows as $id => $row) {
		    
		    
		    // fetch images in each row		    
		    $cells = $scrape->fetchAllBetween('UIPortrait_TALL">','</a></div></div>',$row,true);		    
		    foreach ($cells as $cell) {
		    	
		    	$cell = str_replace('<a class="title"', '<a target="_blank" class="title"', $cell);
		    	// check for new row
		    	if ($i % $this->vars->cells == 0) $return[] = '<tr>';
				
				// print cells
				$return[]	= '<td class="friend">' . substr($cell,17) . '</td>';
		    	$i++;
		    	
		    	// check to end row
		    	if ($i % $this->vars->cells == 0 && $i != 0 ) $return[] = '<tr>';
		    	if ($i > $this->vars->limit) break;
			}
		}
		
		$return[] = '</table>';
		return $return;
	}
	
	
	// output pictures by album id (scraping)
	// change id!
	private function filter_photos() {
		
		// setup scrape tool
		$scrape		= new Scrape();
		$url		= 'http://www.facebook.com/album.php?aid=' . $this->vars->album . '&id=33110006310';
		
		// start scraping
		$scrape->fetch($url);
		$data		= $scrape->removeNewLines($scrape->result);
				
		// select data
		$data = $scrape->fetchBetween('<table class="UIPhotoGrid_Table','</table>',$data,true);
		$rows = $scrape->fetchAllBetween('<tr>','</tr>',$data,true);
			
		// row by row add to table
		$i = 0; 		// cell counter for rows
		$return[] = '<table class="posts photos">';
		foreach ($rows as $id => $row) {
		    
		    
		    // fetch images in each row		    
		    $cells = $scrape->fetchAllBetween('src="','.jpg"',$row,true);		    
		    foreach ($cells as $cell) {
		    	
		    	// check for new row
		    	if ($i % $this->vars->cells == 0) $return[] = '<tr>';
				
				// print cells
				$return[]	= '<td class="photo"><img ' . $cell . ' /></td>';
		    	$i++;
		    	
		    	// check to end row
		    	if ($i % $this->vars->cells == 0 && $i != 0 ) $return[] = '<tr>';
			}
		}
		
		$return[] = '</table>';
		return $return;
	}
	
	
	// output pictures by album id (scraping)
	// change id!
	private function filter_videos() {
		
		// setup scrape tool
		$scrape		= new Scrape();
		$url		= 'http://www.facebook.com/cafecharlatan?v=app_2344061033&ref=ts#!/cafecharlatan?v=app_2392950137&ref=ts';
		
		// start scraping
		$scrape->fetch($url);
		$data		= $scrape->removeNewLines($scrape->result);

		// select data
		$data = $scrape->fetchBetween('<ul id="profile_tabs" class="tabs">','</ul>',$data,true);
		$rows = $scrape->fetchAllBetween('<li>','</li>',$data,true);
		print_r($rows);
			
		// row by row add to table
		$i = 0; 		// cell counter for rows
		$return[] = '<table class="posts videos">';
		foreach ($rows as $id => $row) {
		    
		    
		    // fetch images in each row		    
		    $cells = $scrape->fetchAllBetween('<td class="vTop','</td>"',$row,true);		    
		    foreach ($cells as $cell) {
		    	
		    	// check for new row
		    	if ($i % $this->vars->cells == 0) $return[] = '<tr>';
				
				// print cells
				$return[]	= '<td class="video">' . $cell . '</td>';
		    	$i++;
		    	
		    	// check to end row
		    	if ($i % $this->vars->cells == 0 && $i != 0 ) $return[] = '<tr>';
			}
		}
		
		$return[] = '</table>';
		return $return;
	}
	
	
	// create like button (with iframe, I'm guessing it's impossible to have the same features without, grrrrrr)
	private function filter_like() {
	
		$result[] = '<iframe src="http://www.facebook.com/plugins/like.php?href=' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . 
		'&action=' . $this->action . '&colorscheme=' . $this->vars->color . '&height=' . $this->vars->height . '&width=' . $this->vars->width . 
		'&show_faces=' . $this->vars->faces . '&layout=' . $this->vars->layout . '" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:' . $this->vars->width . 
		'px; height:' . $this->vars->height . 'px;" allowTransparency="true"></iframe>';
		return $result;
	
	}
	
	
	// create recommend button (with iframe, I'm guessing it's impossible to have the same features without, grrrrrr)
	private function filter_recommend() {
	
		$result[] = '<iframe src="http://www.facebook.com/plugins/like.php?href=' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . 
		'&action=' . $this->action . '&colorscheme=' . $this->vars->color . '&height=' . $this->vars->height . '&width=' . $this->vars->width . 
		'&show_faces=' . $this->vars->faces . '&layout=' . $this->vars->layout . '" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:' . $this->vars->width . 
		'px; height:' . $this->vars->height . 'px;" allowTransparency="true"></iframe>';		
		return $result;
	
	}
	
	
	// activities regarding website
	private function filter_activities() {
	
		$result[] = '<iframe src="http://www.facebook.com/plugins/activity.php?site=' . $_SERVER['HTTP_HOST'] . '&width=' . $this->vars->width . '&height=' . $this->vars->height . 
		'&header=false&colorscheme=' . $this->vars->color . '&font=lucida+grande&border_color=black&recommendations=false" scrolling="no" frameborder="0" 
		style="border:none; overflow:hidden; width:' . $this->vars->width . 'px; height:' . $this->vars->width . 'px;" allowTransparency="true"></iframe>';
		return $result;
	}
	
	
	// facebook search for keywords 
	private function filter_keywords() {

		// keywords
		$keywords	= str_replace(' ', '%20', $this->vars->keywords);
		
		// fetch facebook content
		$content	= json_decode(file_get_contents('https://graph.facebook.com/search?q=' . $keywords . '&type=post'));
		
		// loop through content while type selector..
		$i = 0;
		
		$return[] = '<ul class="posts search_items">';
		foreach ($content->data as $post) {
		
			// type
			switch ($this->vars->type) {
				case 'video':
					if (!empty($post->source) && $video != $post->source) {
					
						$movie		= $post->source;
						if (substr($movie,-10) == 'autoplay=1' || substr($movie,-10) == 'autoPlay=1') $movie = substr($movie, 0, -1) . '0';
						
						$return[] 	= '<li class="post ' . $this->vars->type . '">';
						$return[]	= '<object width="' . $this->vars->width . '" height="' . $this->vars->height . '"><param name="movie" value="' . $movie . '"></param>';
						$return[] 	= '<param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param>';
						$return[] 	= '<embed src="' . $movie . '" type="application/x-shockwave-flash" 	
							allowscriptaccess="always" allowfullscreen="true" width="' . $this->vars->width . '" height="' . $this->vars->height . '"></embed></object>';
						$return[] 	= '</li>';
						
						$i++;
						$video		= $post->source;
					}
				
				break;
				
				case 'messages';
					if (empty($post->picture) && !empty($post->message)) {
						$return[] = '<li class="post ' . $this->vars->type . '"><span class="user">' . $post->from->name . ':</span> ' . utf8_decode($post->message) . '</li>';
						$i++;
					}
					
				break;
			}
						
			if ($i == $this->vars->limit) break;

		}
		$return[] = '</ul>';
		
		return $return;
	
	}
	
	
	
	// show personal posts
	private function filter_personal_posts() {
	
		// connect to fb
		$content	= json_decode(file_get_contents('https://graph.facebook.com/' . engine_get("json:social.facebook.account")->account . '/feed?' . $this->connect_fb()));
		$message 	= $this->unshift_content();
		
		// limit foreach and output
		$i = 0;
		
		$return[] = '<ul class="posts personal">';
		foreach ($content->data as $post) {
		
			// type
			switch ($this->vars->type) {
				case 'video':
					if (!empty($post->source) && empty($post->to)) {
					
						$movie		= $post->source;
						if (substr($movie,-10) == 'autoplay=1' || substr($movie,-10) == 'autoPlay=1') $movie = substr($movie, 0, -1) . '0';
						
						$return[] 	= '<li class="post ' . $this->vars->type . '">';
						$return[]	= '<object width="' . $this->vars->width . '" height="' . $this->vars->height . '"><param name="movie" value="' . $movie . '"></param>';
						$return[] 	= '<param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param>';
						$return[] 	= '<embed src="' . $movie . '" type="application/x-shockwave-flash" 	
							allowscriptaccess="always" allowfullscreen="true" width="' . $this->vars->width . '" height="' . $this->vars->height . '"></embed></object>';
						$return[] 	= '</li>';
						
						$i++;
					}
				
				break;
				
				case 'messages';
					if (empty($post->picture) && !empty($post->message) && empty($post->to)) {
						$return[] = '<li class="post ' . $this->vars->type . '"><span class="user">' . $post->from->name . ':</span> ' . html_entity_decode($post->message) . '</li>';
						$i++;
					}
					
				case 'links':
					if ($post->type == 'link') {
						$return[] = '<li class="post ' . $this->vars->type . '">' . html_entity_decode($post->name) . ' 
							<a target="_blank" class="link" href="' . $post->link . '" title="' . html_entity_decode($post->name) . '">' . $message . '</a></li>';
						$i++;
					}
					
				break;
			}
						
			if ($i == $this->vars->limit) break;
			
		}
		$return[] = '</ul>';
		
		return $return;
		
	}
	
	
	// show external posts
	private function filter_external_posts() {
	
		// connect to fb
		$content	= json_decode(file_get_contents('https://graph.facebook.com/' . engine_get("json:social.facebook.account")->account . '/feed?' . $this->connect_fb()));
		
		// limit foreach and output
		$i = 0;
		
		$return[] = '<ul class="posts external">';
		foreach ($content->data as $post) {
			if (!empty($post->to)) {

				$return[] = '<li class="post"><span class="user">' . $post->from->name . ':</span> ' . $post->message . '</li>';
				$i++;
				if ($i == $this->vars->limit) break;
			}
		}
		$return[] = '</ul>';
		
		return $return;
		
	}
	
	
	// show bio
	private function filter_bio() {
	
		// connect to fb
		$content	= json_decode(file_get_contents('https://graph.facebook.com/' . engine_get("json:social.facebook.account")->account . '?' . $this->connect_fb()));
		
		// output bio
		$return[] = '<span class="bio">';
		$return[] = $content->bio;
		$return[] = '</span>';
		
		return $return;
		
	}
	
	
	// show user picture
	private function filter_picture() {
	
		// connect to fb
		$content	= json_decode(file_get_contents('https://graph.facebook.com/' . engine_get("json:social.facebook.account")->account));
		
		// output image
		$return[] = '<a target="_blank" class="link" target="' . $content->link . '"><img class="image" src="' . $content->picture . '" title="' . $content->name . '" /></a>';
		
		return $return;
		
	}
	
	
	// show facebook name
	private function filter_name() {
	
		// connect to fb
		$content	= json_decode(file_get_contents('https://graph.facebook.com/' . engine_get("json:social.facebook.account")->account . '?' . $this->connect_fb()));
		
		// output image
		$return[] = '<span class="name">' . $content->name . '"</span>';
		
		return $return;
		
	}
	
	
	// show user link
	private function filter_link() {
	
		// connect to fb
		$content	= json_decode(file_get_contents('https://graph.facebook.com/' . engine_get("json:social.facebook.account")->account));
		
		// output link
		$return[] = '<a class="facebook_link" href="' . $content->link . '" target="_blank" title="' . $content->name . '">' . $this->unshift_content() . '</a>';
		
		return $return;
		
	}
	
	
	// show fan count
	private function filter_fan_count() {
	
		// connect to fb
		$content	= json_decode(file_get_contents('https://graph.facebook.com/' . engine_get("json:social.facebook.account")->account . '?' . $this->connect_fb()));
		
		// output link
		$return[] = '<span class="fan_count">' . $content->fan_count . '</span>';
		
		return $return;
		
	}
	
	
	// recommand / like news post button
	private function filter_like_post() {
	
		$return[]	= '<a href="http://www.facebook.com/share.php?u=http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . '" target="_blank" class="like">' . $this->vars->text . '</a>';
		return $return;
	
	}	
		
	
	// connect by oauth 2.0
	private function connect_fb() {
		
		// client level facebook variables create access token		
		$page  = number_format(engine_get("json:social.facebook.account")->page, 0, '', '');
		$token = file_get_contents('https://graph.facebook.com/oauth/access_token?type=client_cred&client_id='. $page .'&client_secret='.engine_get("json:social.facebook.account")->appsecret);
		return $token;
	
	}


	/**
	 *	filter facebook feed by id
	 *	file get content for the feed of any page
	 *	@param		string	id
	 *	@param		integer	limit
	 *	@param		type	what
	 *	@return		array
	 */
	 
	private function filter_feed() {
		
		// fetch content
		$url		= 'https://graph.facebook.com/' . $this->vars->id . '/feed?limit=' . (( $this->vars->limit ) ? $this->vars->limit : '5' );
		$content	= json_decode( @file_get_contents( $url ));
		
		// output content
		$return[]		= '<ul class="feed">';
		foreach( $content->data as $feed ) {
			
			$from		= '<span class="from"><a href="http://facebook.com/profile.php?id=' . $feed->from->id . '" target="_blank">' . $feed->from->name . '</a></span>';
			$time		= '<span class="time">' . date( 'd/m H:i', strtotime( $feed->created_time )) . '</span>';
			
			if( $feed->type == 'photo' && ( !$this->vars->type || $this->vars->type == 'photo' )) {
				$cont	= '<a href="' . $feed->link . '" target="_blank" title="' . $feed->name . '">';
				$cont  .= '<img src="' . $feed->picture . '" alt="' . $feed->name . '" /><span class="content">' . $feed->name . '</span>';
				$cont  .= '</a>';
				
				$return[] 	= '<li class="feed_item">' . $cont . $from . $time . '</li>';
			} else if( $feed->type == 'status' && ( !$this->vars->type || $this->vars->type == 'message' ) && strlen( $feed->message ) > 2 ) {
				$cont  = '<span class="content">' . $feed->message . '</span>';
			
				$return[] 	= '<li class="feed_item">' . $cont . $from . $time . '</li>';
			} else if( $feed->type == 'link' && ( !$this->vars->type || $this->vars->type == 'link' ) ) {
			
				if( strlen( $feed->picture ) > 70 ) {
					$cont  = '<span class="content"><a href="' . $feed->link . '" target="_blank" title="' . $feed->name . '">';
					$cont .= $feed->name . '</a></span>';
				} else {
					$cont	= '<a href="' . $feed->link . '" target="_blank" title="' . $feed->name . '">';
					$cont  .= '<img src="' . $feed->picture . '" alt="' . $feed->name . '" /><span class="content">' . $feed->name . '</span>';
					$cont  .= '</a>';
				}
				$return[] 	= '<li class="feed_item">' . $cont . $from . $time . '</li>';
			} else if( $feed->type == 'video' && ( !$this->vars->type || $this->vars->type == 'video' ) ) {
				$cont	= '<a href="' . $feed->link . '" target="_blank" title="' . $feed->name . '">';
				$cont  .= '<img src="' . $feed->picture . '" alt="' . $feed->name . '" /><span class="content">' . $feed->name . '</span>';
				$cont  .= '</a>';
				
				$return[] 	= '<li class="feed_item">' . $cont . $from . $time . '</li>';
			}
			
		}
		$return[]		= '</ul>';
		
		return $return;
	}
	 
	

	
	
	/**
	 * iframe integration such as
	 * like button, login, like, live stream, comments, facepile...
	 * see http://developers.facebook.com/plugins for more info
	 *
	 * @param	array - vars
	 * @return	string
	 */
	private function filter_iframe() {
	
		// params
		$width 		= (( $this->vars->width ) ? $this->vars->width : 450 );
		$height		= (( $this->vars->height ) ? $this->vars->height : 21 );
		$font 		= (( $this->vars->font ) ? $this->vars->font : 'arial' );
		$layout		= (( $this->vars->layout ) ? $this->vars->layout : 'standard' );
		$color 		= (( $this->vars->color ) ? $this->vars->color : 'light' );
		$faces 		= (( $this->vars->faces ) ? $this->vars->faces : 'true' );
		$verb 		= (( $this->vars->verb ) ? $this->vars->verb : 'like' );
		$url		= (( $this->vars->url ) ? $this->vars->url : engine_get( 'url' ));
		$header		= (( $this->vars->header ) ? $this->vars->header : 'false' );
		$stream		= (( $this->vars->stream ) ? $this->vars->stream : 'false' );
		$connections= (( $this->vars->connections ) ? $this->vars->connections : '10' );
		$rows		= (( $this->vars->rows ) ? $this->vars->rows : '1' );
					 
					 
		// add class
		$this->addclass( $this->vars->type );
				
				
		// switch type of iframe
		switch( $this->vars->type ) {
		
			// like button
			// layout style		button_count / box_count / standard
			// verb to display	like / recommend
			// color scheme  	light / dark
			// show faces		true / false
			// font 			arial / lucida grande / segoe ui / tahoma / trebuchet ms /  verdana
			case 'like':
				$result[] = '<iframe src="http://www.facebook.com/plugins/like.php?href=' . urlencode( $url ) . '&amp;layout=' . $layout . '&amp;show_faces=' . $faces . '&amp;width=' . $width . '&amp;action=' . $verb . '&amp;font=' . $font . '&amp;colorscheme=' . $color . '&amp;height=' . $height . '" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:' . $width . 'px; height:' . $height . 'px;" allowTransparency="true"></iframe>';
				
				break;
				
			case 'livestream':
				$result[] = '<iframe src="http://www.facebook.com/plugins/live_stream_box.php?app_id=' . engine_get( 'json:social.facebook.account' )->appid . '&amp;width=' . $width . '&amp;height=' . $height . '&amp;via_url&amp;always_post_to_friends=true" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:' . $width . 'px; height:' . $height . 'px;" allowTransparency="true"></iframe>';
				
				break;
				
			case 'recommend':
				$result[] = '<iframe src="http://www.facebook.com/plugins/recommendations.php?width=' . $width . '&amp;site=' . urlencode( $url ) . '&amp;height=' . $height . '&amp;header=' . $header . '&amp;colorscheme=' . $color . '" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:' . $width . 'px; height:' . $height . 'px;" allowTransparency="true"></iframe>';
				
				break;
				
			case 'likebox':
				$result[] = '<iframe src="http://www.facebook.com/plugins/likebox.php?id=' . urlencode( $url ) . '&amp;width=' . $width . '&amp;colorscheme=' . $color . '&amp;connections=' . $connections . '&amp;stream=' . $stream . '&amp;header=' . $header . '&amp;height=' . $height . '" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:' . $width . 'px; height:' . $height . 'px;" allowTransparency="true"></iframe>';
				
				break;
				
			case 'login':
				$result[] = '<div id="fb-root"></div><script src="http://connect.facebook.net/en_US/all.js#appId=' . engine_get( 'json:social.facebook.account' )->appid . '&amp;xfbml=1"></script><fb:login-button show-faces="' . $faces . '" width="' . $width . '" max-rows="' . $rows . '"></fb:login-button>';
				
				break;	
				
			case 'activity':
				$result[] = '<iframe src="http://www.facebook.com/plugins/activity.php?site=' . urlencode( $url ) . '&amp;width=' . $width . '&amp;height=' . $height . '&amp;header=' . $header . '&amp;colorscheme=' . $color . '&amp;recommendations=true&amp;font=' . $font . '" scrolling="no" frameborder="0" border_color="#4A4A4A" style="border:none; overflow:hidden; width:' . $width . 'px; height:' . $height . 'px;" allowTransparency="true"></iframe>';
				
				break;		
				
			case 'facepile':
				$result[] = '<iframe src="http://www.facebook.com/plugins/facepile.php?href=' . urlencode( $url ) . '&amp;width=' . $width . '&amp;max_rows=' . $rows . '" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:' . $width . 'px;" allowTransparency="true"></iframe>';
				
				break;
				
			case 'facepile2':
				$result[] = '<div id="fb-root"></div><script src="http://connect.facebook.net/en_US/all.js#appId=' . engine_get( 'json:social.facebook.account' )->appid . '&amp;xfbml=1"></script><fb:facepile max-rows="' . $rows . '" href="' . $url . '" width="' . $width . '"></fb:facepile>';		
				
				break;
				
			case 'comments';
				$result[] = '<div id="fb-root"></div><script src="http://connect.facebook.net/en_US/all.js#appId=' . engine_get( 'json:social.facebook.account' )->appid . '&amp;xfbml=1"></script><fb:comments width="' . $width . '" numposts="' . $rows . '"></fb:comments>';
				
				break;
		}
		
		return $result;
	}
		
}




class Scrape {


	public $headers = array();

	public $result;

	public $error;



	function __construct() {

		return true;

	}



	function setHeader($header) {

		$this->headers[] = $header;

	}



	function fetch($url, $data=''){


		$ch = curl_init();

		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_FRESH_CONNECT,true);
		curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"); 
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 


		if (is_array($data) && count($data)>0){

			curl_setopt($ch, CURLOPT_POST, true);
			$params = http_build_query($data);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $params);

		}


		if (is_array($this->headers) && count($this->headers)>0){

			curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);

		}


		$this->result = curl_exec($ch);
		$this->error = curl_error($ch);
		curl_close($ch);	

	}



	function fetchBefore($needle,$haystack,$include=false){

		$included = strpos($haystack,$needle) + strlen($needle);
		$excluded = strpos($haystack,$needle);

		if ($included === false || $excluded === false) { return null; }

		$length = ($include == true) ? $included : $excluded ;

		$substring = substr($haystack, 0, $length);

		return trim($substring);

	}



	function fetchAfter($needle,$haystack,$include=false){

		$included = strpos($haystack,$needle);
		$excluded = strpos($haystack,$needle) + strlen($needle);

		if ($included === false || $excluded === false) { return null; }

		$position = ($include == true) ? $included : $excluded ;

		$substring = substr($haystack, $position, strlen($haystack) - $position);

		return trim($substring);

	}



	function fetchBetween($needle1,$needle2,$haystack,$include=false){

		$position = strpos($haystack,$needle1);
		if ($position === false) { return null; }

		if ($include == false) $position += strlen($needle1);

		$position2 = strpos($haystack,$needle2,$position);
		if ($position2 === false) { return null; }

		if ($include == true) $position2 += strlen($needle2);

		$length = $position2 - $position;

		$substring = substr($haystack, $position, $length);

		return trim($substring);

	}



	function fetchAllBetween($needle1,$needle2,$haystack,$include=false){

		$matches = array();
		$exp = "|{$needle1}(.*){$needle2}|U";

		preg_match_all($exp,$haystack,$matches);

		$i = ($include == true) ? 0 : 1 ;

		return $matches[$i];

	}



	function removeNewlines($input){

		return str_replace(array("\t","\n","\r","\x20\x20","\0","\x0B"), "", html_entity_decode($input));

	}



	function removeTags($input,$allowed=''){

		return strip_tags($input,$allowed);

	}



}

/*
///////////////  FACEBOOK  //////////////////
if($MOD->tool=="facebook") {
////////////////////////////////////////////////

	if($MOD->action == "fanclub") {
		$active = ( $_set->hold )? "FB.holdkey = \"" . engine_get("json:social.facebook.account")->appapi . "\"": "FB.init(\"" . engine_get("json:social.facebook.account")->appapi . "\");";
	
		return $MOD->_parse("<script type=\"text/javascript\" src=\"http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/nl_NL\"></script>
			<script type=\"text/javascript\">$active</script>
			<fb:fan profile_id=\"" . engine_get("json:social.facebook.account")->page . "\" stream=\"0\" connections=\"". $_set->connections . "\" logobar=\"0\" width=\"" . $_set->dimensions[0] . "\" height=\"" . $_set->dimensions[1] . "\"></fb:fan>
			<div style=\"font-size:8px; padding-left:10px\"><a href=\"http://www.facebook.com/profile.php?id=" . engine_get("json:social.facebook.account")->page . "\">" . engine_get('mail.ext') . "</a> on Facebook</div>");
	}
	
	
	else if($MOD->action == "connect") {
		#
		# Connect Facebook account to site.
		#
		require_once(ROOT.'/../ext/facebook/facebook.php');
		$fb = new Facebook(engine_get("json:social.facebook.account")->appapi, engine_get("json:social.facebook.account")->appsecret);
		try {
		    $uid = $fb->api_client->users_getLoggedInUser();
		} catch (Exception $e) {
		    $uid = null; // No user logged in.
		}
		
		// Generate Javascript part
		$ret_string = "<script type=\"text/javascript\" src=\"http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php\"></script>";
		$ret_string = "<script type=\"text/javascript\">
				function reload() {
					javascript:location.reload();
	 			}
	 		</script>";
		if ($uid) {
			// User is logged in and connected via Facebook
			$user_inf = $fb->api_client->users_getInfo($uid, 'first_name', 'last_name');
			$user_obj = $DB->short('ID', 'mod_user', 'openid=' . $uid);
			if (!$user_obj) {
				# Create user!
				$user_details = $fb->api_client->users_getInfo($uid, 'last_name , first_name');
				$sqlcmd = "INSERT INTO mod_user (lang, fname, lname, openid) VALUES ('nl', '" . $user_details[0]['first_name'] . "', '" . $user_details[0]['last_name'] . "', " . $uid . ")";
				$DB->tube($sqlcmd);
				$user_obj = mysql_insert_id();
			}
			$ret_string .= "<h3>Hi, " . $user_inf[0]['first_name'] . "</h3>";
			$ret_string .= "<fb:profile-pic uid='loggedinuser' size='square' facebook-logo='true'></fb:profile-pic>";
			$ret_string .= ' <a href="#" onclick="FB.Connect.logout(reload); return false;" ><img id="fb_logout_image" src="http://static.ak.fbcdn.net/images/fbconnect/logout-buttons/logout_small.gif" alt="Connect"/></a>';
			
			$event_id = $_GET['id'];
			$event_info = $DB->parse('nameid, type', 'mod_object', 'id='.$event_id);
			
			$fb_type = $DB->short('ID', '`types`', '`key`="social.facebook"');
			
			
			$ret_string .= "<script>
		
				var Attendance = function ( type, user_id, event_id, event_type ) {
					this.type = type;
					this.user_id = user_id;
					this.event_id = event_id;
					this.event_type = event_type;
				}
				
				var att = new Attendance(" . $fb_type . ", " . $user_obj . ", " . $event_id . ", " . $event_info['type'] . ");
	 			
				function callPublish(msg, attachment, action_link) {
				  FB.ensureInit(function () {
				    FB.Connect.streamPublish(msg, attachment, action_link, null, '', callback=attendance_create);
				  });
				}
	 			
	 			function attendance_create(post_id, exception) {
	 				if (post_id) {
		 				new Ajax.Request('/attendance_update.php', {
		 					method: 'post',
		 					parameters: {action:'create', type:att.type, user_id:att.user_id, event_id:att.event_id, event_type:att.event_type},
		 					onSuccess: function() {reload()},
		 				});
	 				}
	 			}
	 			
	 			function attendance_delete(type, user_id, event_id, event_type) {
	 				new Ajax.Request('/attendance_update.php', {
	 					method: 'post',
	 					parameters: {action:'delete', type:type, user_id:user_id, event_id:event_id, event_type:event_type},
	 					onSuccess: function() {reload()},
	 				});
	 			}
	 			
	 			</script>";
	
			
			// Has the user RSVP'd?
			if($DB->short('ID', 'glue_social', 'parenttype=' . $fb_type . ' AND objid=' . $event_id . ' AND objtype=' . $event_info['type'] . ' AND parentid=' . $user_obj)) {
				$ret_string .= "<p>You are going to this event. Changed your mind? <a href='#' onclick='attendance_delete(" . $fb_type . ", " . $user_obj . ", " . $event_id . ", " . $event_info['type'] . ")'>Cancel</a>.</p>";
			}
			else {
				$ret_string .= "<p><a href='#' onclick='callPublish(\"I&rsquo;m going to see ". $DB->lang($event_info['nameid']) . " on Jazz and Sounds!\", null, [{\"href\":\"http://jazzandsounds.com/bio/?id=" . $event_id . "\", \"text\":\"Check it out!\"}])'>Click here</a> if you are going to this event.</p>";
			}
						
			// Get RSVPs to this event
			
			$rsvps = $DB->parse('parentid', 'glue_social', 'parenttype=' . $fb_type . ' AND objid=' . $event_id .' AND objtype=' . $event_info['type'], true);
			if ($rsvps) {
				$ret_string .= "<h3>These people are going</h3>";
				$ret_string .= "<div class='attenders'>";
				foreach ($rsvps as $rsvp) {
					$fbid = $DB->short('openid', 'mod_user', 'ID='. $rsvp['parentid']);
					$ret_string .= "<fb:profile-pic size='square' uid='" . $fbid . "' facebook-logo='false'></fb:profile-pic>";
				}
				$ret_string .= "</div>";
			}
		}
		else {
			$ret_string .= "<div id='going'>I'm going! <span>(click here)</span></div>";
			$ret_string .= "<div id='facebook'>";
			// User is not yet connected.
			$ret_string .= "<p>Sign in with Facebook to tell your friends about this event and to see who is going.</p>";
			$ret_string .= '<fb:login-button onlogin="reload()" v="2"></fb:login-button>';

		}
		$ret_string .= "</div>";
		$ret_string .= "<script type=\"text/javascript\">
			FB.init(\"" . engine_get("json:social.facebook.account")->appapi . "\", \"xd_receiver.htm\")
		</script>";

		return $MOD->_parse($ret_string);
	}
	
}

	
/*	public function output() {
		
		
		if( $this->action )
			$result = $this->{ "filter_" . $this->action }();
		
		$result .= '<script>FB.init("' . engine_get("json:social.facebook.account")->appapi . '", "xd_receiver.htm");</script>';
	
	
		return $result;
		
	}
	
	private function filter_fanclub() {
		return '<fb:fan profile_id="' . engine_get("json:social.facebook.account")->page . '" stream="0" connections="' . $this->vars->connections . '" logobar="0" width="' . $this->vars->width . '" height="' . $this->vars->height . '"></fb:fan>';
	}
	
	private function filter_connect() {
		require_once(ROOT.'/../ext/facebook/facebook.php');
		$fb = new Facebook(
			engine_get("json:social.facebook.account")->appapi, 
			engine_get("json:social.facebook.account")->appsecret
		);
		try {
		    $uid = $fb->api_client->users_getLoggedInUser();
		} catch (Exception $e) {
		    $uid = null; // No user logged in.
		}
		if ($uid) { // If the user is logged in.
			// User is logged in and connected via Facebook
			$user_inf = $fb->api_client->users_getInfo($uid, 'first_name', 'last_name');
			
			# Not really working, user type has not been created. Also should be a get() call. Only one user should match. 
			$user_obj = $DB->filter(
				'user', 
				'openid=' . $uid
			);
			
			$user_obj = $user_obj[0];
			if (!$user_obj) {
				# Create user
				$user_details = $fb->api_client->users_getInfo(
					$uid, 
					'last_name , first_name'
				);
				$sqlcmd = "INSERT INTO mod_user (lang, fname, lname, openid) VALUES ('nl', '" . $user_details[0]['first_name'] . "', '" . $user_details[0]['last_name'] . "', " . $uid . ")";
				$DB->query($sqlcmd);
				$user_obj = mysql_insert_id();
			}
			$ret_string .= "<h3>Hi, " . $user_inf[0]['first_name'] . "</h3>";
			$ret_string .= "<fb:profile-pic uid='loggedinuser' size='square' facebook-logo='true'></fb:profile-pic>";
			$ret_string .= ' <a href="#" onclick="FB.Connect.logout(reload); return false;" ><img id="fb_logout_image" src="http://static.ak.fbcdn.net/images/fbconnect/logout-buttons/logout_small.gif" alt="Connect"/></a>';
			
			$event_id = $_GET['id'];
			$event_info = $DB->filter_key(
				'facebook', 
				'id='.$event_id,
				array('nameid, type')
			);
	
			
			// Has the user RSVP'd?
			if($DB->short('ID', 'glue_social', 'parenttype=<%type:social.facebook%> AND objid=' . $event_id . ' AND objtype=' . $event_info['type'] . ' AND parentid=' . $user_obj)) {
				$ret_string .= "<p>You are going to this event. Changed your mind? <a href='#' onclick='attendance_delete(<%type:social.facebook%>, " . $user_obj . ", " . $event_id . ", " . $event_info['type'] . ")'>Cancel</a>.</p>";
			}
			else {
				$ret_string .= "<p><a href='#' onclick='callPublish(\"I&rsquo;m going to see ". $DB->lang($event_info['nameid']) . " on Jazz and Sounds!\", null, [{\"href\":\"http://jazzandsounds.com/bio/?id=" . $event_id . "\", \"text\":\"Check it out!\"}])'>Click here</a> if you are going to this event.</p>";
				$ret_string = "<script>var att = new Attendance(<%type:social.facebook%>, " . $user_obj . ", " . $event_id . ", " . $event_info['type'] . ");</script>";
			}
						
			// Get RSVPs to this event
			
			$rsvps = $DB->parse('parentid', 'glue_social', 'parenttype=<%type:social.facebook%> AND objid=' . $event_id .' AND objtype=' . $event_info['type'], true);
			if ($rsvps) {
				$ret_string .= "<h3>These people are going</h3>";
				$ret_string .= "<f class='attenders'>";
				foreach ($rsvps as $rsvp) {
					$fbid = $DB->short('openid', 'mod_user', 'ID='. $rsvp['parentid']);
					$ret_string .= "<fb:profile-pic size='square' uid='" . $fbid . "' facebook-logo='false'></fb:profile-pic>";
				}
				$ret_string .= "</div>";
			}
		}
		else {
			$ret_string .= "<div id='going'>I'm going! <span>(click here)</span></div>";
			$ret_string .= "<div id='facebook'>";
			// User is not yet connected.
			$ret_string .= "<p>Sign in with Facebook to tell your friends about this event and to see who is going.</p>";
			$ret_string .= '<fb:login-button onlogin="reload()" v="2"></fb:login-button>';

		}
		$ret_string .= "</div>";

		
		return $ret_string;
	}
}*/
?>